<?php
namespace App\Controller;

use lib\View;
use App\Model\Gallery;

class GalleryController
{
	public function index()
	{
		$user = $_SESSION['user'];
		    if (empty($user)) {
		    	header('Location:' . url('auth/signin'));
		    	return;
		    }
		    $galleryList = Gallery::get(['user.id' => $user->id]);
		    return new View('gallery.index', ['user' => $user, 'galleryList' => $galleryList]);
	}

	public function detail()
	{
		$id = $this->input('id');
		$gallery = Gallery::find(['id' => $id]);
		// return (new View('gallery.detail'))->with('gallery',$gallery);
		$user = $_SESSION['user'];
		return new View('gallery.detail',['user' => $user, 'gallery' => $gallery]);

	}

	public function create()
	{
		return new View('gallery.create');
	}

	public function addImg()
	{
		return new View('gallery/add',['id' => $_GET['id']]);
	}
    
    // 添加图片
	public function addImages()
	{
		$id = $this->input('gid');

		$gallery = new Gallery();
		$gallery = $gallery->find(['id' => $id]);

		// 调用upload处理上传图片
		$gallery->upload();
		$gallery->save();

		header('Location:' . url('gallery/detail',['id' => $id]));
	}
    
    // 删除相册
	public function deleteGallery()
	{
		$id = $this->input('id');
		// 	要删除相册的绝对路径
		$path = STORAGE_DIR . DIRECTORY_SEPARATOR . 'gallery' . DIRECTORY_SEPARATOR . $id . '.json';

		$gallery = Gallery::find(['id' => $id]);
        // 删除对应的图片
		foreach ($gallery->imageCollection as $img) {
			$imagePath = PUBLIC_DIR . DIRECTORY_SEPARATOR . $img->path;
			unlink($imagePath);
		}
		// 删除相册对应的Json文件
		unlink($path);
		header('Location:' . url('index'));
	}

	public function store()
	{
		// 创建Gallery对象实例
		$gallery = new Gallery();
		$gallery->id = $this->input('id');
		$gallery->title = $this->input('title');
		$gallery->description = $this->input('description');
		$gallery->created_at = time();
		$gallery->updated_at = $gallery->created_at;

		$user = $_SESSION['user'];
		$gallery->user = $user;

		// 处理上传图片 
		$gallery->upload();
		// 保存相册数据
		$gallery->save();
		header('Location:' . url('index'));
	}

           private function input($name)
           {
           	          return htmlspecialchars(stripslashes($_REQUEST[$name]));
           }
}